package com.example.mp.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mp.bo.AccountBo;
import com.example.mp.entity.UserEntity;
import com.example.mp.exception.BusinessException;
import com.example.mp.mapper.UserMapper;
import com.example.mp.service.UserService;
import com.example.mp.utils.ExcelUtils;
import com.example.mp.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.concurrent.CountDownLatch;


@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
    @Override
    @DS("master")
    public List<UserEntity> getMasterUserList() {
        return this.list();
    }

    @Override
    @DS("slave_1")
    public List<UserEntity> getSlaveOneUserList() {
        return this.list();
    }

    @Override
    @DS("slave_2")
    public List<UserEntity> getSlaveTwoUserList() {
        return this.list();
    }

    @Override
    @DS("master")
    public AccountBo login(AccountBo accountBo) {
        UserEntity entity = this.getOne(new QueryWrapper<UserEntity>().eq("name", accountBo.getName()).eq("passwd", accountBo.getPasswd()));
        if (ObjectUtils.isEmpty(entity)) {
            throw new BusinessException(500, "用户名和密码不匹配");
        }
        String token = JWTUtils.getToken(accountBo);
        log.info("token:" + token);
        //以 key = token  value =用户信息 存入Redis
        return accountBo;
    }

    @Override
    public void exportUser() {
        List<UserEntity> list = this.list(new QueryWrapper<UserEntity>().lt("id", 200));
        ExcelUtils.exportData(list, UserEntity.class);
    }

    @Override
    @Transactional
    @Async("asyncServiceExecutor")
    public void insertUser(List<UserEntity> listSub, CountDownLatch countDownLatch) {
        try {
            this.saveBatch(listSub);
            log.info("线程" + Thread.currentThread().getName() + "插入" + listSub.size() + "条数据");
        } finally {
            countDownLatch.countDown();
        }
    }

    @Override
    public void sayHi(String str) {
        System.out.println(str + "hello world!");
    }
}
